using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using LMSData;

public partial class Admin_ManageUsers : System.Web.UI.Page
{

    UserController ucontrol = new UserController();


    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Roles.IsUserInRole(Membership.GetUser().UserName, "Admin"))
                Response.Redirect("~/");
        }
        catch 
        {
            Response.Redirect("~/");
        }

        if (!IsPostBack)
        {
            BindUsers();
            BindRoles();
            BindGroups();
        }

    }

    private void BindUsers()
    {
        UserCollection uc = new UserCollection();
        if (radActive.SelectedValue == "All")
        {
            uc = ucontrol.FetchAll();
        }
        else
        {

            uc = ucontrol.FetchAll(Convert.ToBoolean(radActive.SelectedValue));
        }
        
        uc.Sort(LMSData.User.Columns.Email,true);
        grdUsers.DataSource = uc;
        grdUsers.DataBind();
        update1.Update();
    }

    private void BindRoles()
    {
        string[] rls = Roles.GetAllRoles();
        chklstRoles.DataSource = rls;
        chklstRoles.DataBind();
    }

    private void BindRoles(string username)
    {
        string[] urls = Roles.GetRolesForUser(username);
        string[] rls = Roles.GetAllRoles();
        ListItem li;
        chklstEditRoles.Items.Clear();
        foreach (string rl in rls)
        {
            li = new ListItem();
            li.Text = rl;
            foreach (string url in urls)
            {
                if (url == rl)
                    li.Selected = true;
            }
            chklstEditRoles.Items.Add(li);
        }
        
    }

    private void BindGroups()
    {
        cblGroups.DataSource = LMSData.GroupController.GetGroups();
        cblGroups.DataBind();
    }

    protected void grdUsersRowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName != "Select")
        {
            if (e.CommandName == "Assign")
            {
                Control c = e.CommandSource as Control;
                if (c != null)
                {
                    UserID.Value = e.CommandArgument.ToString();

                    cblCourses.DataSource = CourseController.GetCourses();
                    cblCourses.DataBind();
                    foreach (ListItem li in cblCourses.Items)
                    {
                        li.Selected = false;
                        foreach (Course crs in UserController.GetCourses(UserID.Value))
                        {
                            if (li.Value == crs.CourseID.ToString())
                                li.Selected = true;
                        }
                    }

                    UpdatePanelPopupExtender3.ShowAt(c);
                }
            }
            else
            {
                update1.Update();
            }
        }
        else
        {
            
            Control c = e.CommandSource as Control;
            if (c != null)
            {
                // User
                MembershipUser usr = Membership.GetUser(Convert.ToInt32(e.CommandArgument));
                txtEditUsername.Text = usr.Email;
                chkApproved.Checked = usr.IsApproved;
                chlLockedOut.Checked = usr.IsLockedOut;

                // Profile
                ProfileCommon p = new ProfileCommon();
                p = Profile.GetProfile(usr.UserName);
                txtEditFirstName.Text = p.FirstName;
                txtEditLastName.Text = p.LastName;

                // Roles
                BindRoles(usr.UserName);

                UpdatePanelPopupExtender2.ShowAt(c);
                
            }
        }

        //Novations.ROI.User usr = new User();
        
    }

    protected void OpenAssignGroups(object sender, CommandEventArgs e)
    {
        LMSData.GroupCollection gc = LMSData.UserController.GetGroups(e.CommandArgument.ToString());
        foreach (ListItem li in cblGroups.Items)
        {
            li.Selected = false;
            foreach (LMSData.Group grp in gc)
            {
                if (li.Value == grp.GroupID.ToString())
                {
                    li.Selected = true;
                    break;
                }
            }
        }
        UpdatePanelPopupExtender4.ShowAt((LinkButton)sender);
        UserID.Value = e.CommandArgument.ToString();
    }

    protected void grdDeleted(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int) grdUsers.DataKeys[e.RowIndex].Value;
        LMSData.User usr = new LMSData.User();
        usr.LoadByKey(ID);
        usr.IsDeleted = true;
        usr.Save();
        //ucontrol.Delete(ID);
        BindUsers();   
    }

    protected void radActive_Click(object sender, EventArgs e)
    {
        BindUsers();
    }

    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        // Create User
        MembershipUser usr = Membership.CreateUser(txtUserName.Text, txtPassword1.Text, txtUserName.Text);
        
        // Create Profile
        ProfileCommon p = new ProfileCommon();
        p = Profile.GetProfile(txtUserName.Text);
        p.FirstName = txtFirstname.Text;
        p.LastName = txtLastName.Text;
        
        p.Save();
        
        BindUsers();
    }

    protected void btnSaveEdit_Click(object sender, EventArgs e)
    {

        // Edit User
        MembershipUser usr = Membership.GetUser(Convert.ToInt32(grdUsers.SelectedDataKey.Value));
        usr.Email = txtEditUsername.Text;
        if (txtEditPassword1.Text != String.Empty)
        {
            usr.ChangePassword(usr.GetPassword(), txtEditPassword1.Text);
        }
        //usr.UserName = txtEditUsername.Text;
        if (usr.IsLockedOut && !chlLockedOut.Checked) usr.UnlockUser();
        
        usr.IsApproved = chkApproved.Checked;
        Membership.UpdateUser(usr);

        // Edit Profile
        ProfileCommon p = new ProfileCommon();
        p = Profile.GetProfile(usr.UserName);
        p.FirstName = txtEditFirstName.Text;
        p.LastName = txtEditLastName.Text;
        p.Save();
        
        foreach(ListItem li in chklstEditRoles.Items)
        {
            if (!li.Selected)
            {
                if (Roles.IsUserInRole(usr.UserName, li.Text))
                    Roles.RemoveUserFromRole(usr.UserName, li.Text);
            }
            else
            {
                if (!Roles.IsUserInRole(usr.UserName, li.Text))
                    Roles.AddUserToRole(usr.UserName, li.Text);
            }
        }

        // Rebind
        grdUsers.SelectedIndex = -1;
        update1.Update();
        UpdatePanelPopupExtender2.Hide();

        BindUsers();

    }

    protected void btnCancelEdit_Click(object sender, EventArgs e)
    {
        grdUsers.SelectedIndex = -1;
        update1.Update();
        UpdatePanelPopupExtender2.Hide();
    }

    protected void UpdatePanelPopupExtender2_Close(object sender, EventArgs e)
    {
        grdUsers.SelectedIndex = -1;
        //DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
    }

    protected void UpdatePanelPopupExtender4_Close(object sender, EventArgs e)
    {
    }

    protected void PageChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.PageIndex = e.NewPageIndex;
        BindUsers();
    }

    protected void btnSaveCourses_Click(object sender, EventArgs e)
    {
        LMSData.UserCourseMap.Delete(LMSData.UserGroupMap.Columns.UserID, UserID.Value);

        foreach (ListItem li in cblCourses.Items)
        {
            LMSData.UserCourseMap ucm = new UserCourseMap();
            if (li.Selected)
            {
                ucm.UserID = Int32.Parse(UserID.Value);
                ucm.CourseID = Int32.Parse(li.Value);
                ucm.Save();
            }
        }
        grdUsers.SelectedIndex = -1;
        update1.Update();
        UpdatePanelPopupExtender3.Hide();
    }

    protected void AssignGroups(object sender, EventArgs e)
    {
        LMSData.UserGroupMap.Delete(LMSData.UserGroupMap.Columns.UserID, UserID.Value);

        foreach (ListItem li in cblGroups.Items)
        {
            LMSData.UserGroupMap ugm = new UserGroupMap();
            if (li.Selected)
            {
                ugm.UserID = Int32.Parse(UserID.Value);
                ugm.GroupID = Int32.Parse(li.Value);
                ugm.Save();
            }
        }
        update1.Update();
        UpdatePanelPopupExtender4.Hide();
    }

    protected void CancelGroups(object sender, EventArgs e)
    {
        UpdatePanelPopupExtender4.Hide();
    }
    
}
